<?php

namespace Modules\Admin\Http\Controllers\Ebooks;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Modules\Common\General\Security\Api\Gateway;
use Modules\Common\Models\AdminLog;
use Modules\Common\Models\Ebooks;
use Modules\Common\Models\EbookChapters;
use Modules\Common\Models\EbookSections;
use Modules\Common\Models\File;
use Modules\Common\Util\Api;
use Modules\Common\Util\Database;
use PdfReader\PdfReader;
use TextReader\TextReader;


class Import
{
    
     public function __construct()
    {
        $this->textReader = new TextReader();
        $this->pdfReader = new PdfReader();
    }
    
    
   /**
     * @Route(path=/api/admin/ebook/import method=post)
     */
    public function import()
    {
        Api::validate(['fileId' => 'required']);
        $filePath =  File::getUrl(request('fileId'));
        $book = $this->parseContent($filePath);
        $eidDefault = auth('api')->user()->eid; 
        $sidDefault = auth('api')->user()->sid;
        $bookId = request('book_id');
        if ($book) {
            // 获取所有匹配的章节ID
            $chapterIds = DB::table('ebook_chapters')
                ->where('ebook_id', $bookId)
                ->pluck('id')
                ->toArray();
            // 删除这些章节下的节记录
            $deletedCount = DB::table('ebook_sections')->whereIn('chapter_id', $chapterIds)
                ->delete();
            // 删除这些章节记录
            $deletedCount = DB::table('ebook_chapters')
                ->whereIn('id',$chapterIds)
                ->delete();
                
            //读取文本统计章数
            $chapterCount = count($book);
            $sectionCount = 0;
            // 开启数据库事务
            DB::beginTransaction();
            try {
                // 遍历每个章节
                foreach ($book as $index => $chapter) {
                    // 检查章节是否已存在
                    $chapterExists = DB::table('ebook_chapters')
                        ->where('ebook_id', request('book_id'))
                        ->where('chapter_number', $chapter['chapter_number'])
                        ->exists();
                    
                    if (!$chapterExists) {
                        // 插入章节到 EbookChapters 表
                        $chapterId = DB::table('ebook_chapters')->insertGetId([
                            'ebook_id' => request('book_id'),
                            'eid' => $eidDefault,
                            'sid' => $sidDefault,
                            'chapter_number' => $chapter['chapter_number'],
                            'chapter_title' => $chapter['chapter_title'],
                            'created_at' => date('Y-m-d H:i:s')
                        ]);
                    } else {
                        // 如果章节已存在，获取章节 ID
                        $chapterId = DB::table('ebook_chapters')
                            ->where('ebook_id', request('book_id'))
                            ->where('chapter_number', $chapter['chapter_number'])
                            ->value('id');
                    }
        
                    // 统计节数并插入节到 EbookSections 表
                    foreach ($chapter['sections'] as $section) {
                        $sectionExists = DB::table('ebook_sections')
                            ->where('chapter_id', $chapterId)
                            ->where('section_number', $section['section_number'])
                            ->exists();
                        
                        if (!$sectionExists) {
                            $sectionCount++;
                            DB::table('ebook_sections')->insert([
                                'chapter_id' => $chapterId,
                                'eid' => $eidDefault,
                                'sid' => $sidDefault,
                                'section_number' => $section['section_number'],
                                'section_title' => $section['section_title'],
                                'content' => $section['content'],
                                'created_at' => date('Y-m-d H:i:s')
                            ]);
                        }
                        // 如果节已存在，可以选择更新内容或跳过
                    }
                }
        
                // 更新电子书相关参数
                Ebooks::where('id', request('book_id'))->update([
                    'total_chapter_count' => $chapterCount,
                    'total_sections_count' => $sectionCount,
                ]);
        
                // 提交事务
                DB::commit();
                return Api::success();
            } catch (\Exception $e) {
                // 回滚事务
                DB::rollBack();
                return Api::fail($e->getMessage());
            }
        }else{
             return Api::fail();
        }
        
    }
    protected function parseContent($filePath)
    {
        $extension = pathinfo($filePath, PATHINFO_EXTENSION);
        switch ($extension) {
            case 'txt':
                $fileContent =  $this->textReader->readTxtFile($filePath);
                return $fileContent;
            case 'pdf':
                $info = $this->pdfReader->readPdfFile($filePath);
                return $info;
            default:
                return null;
        }
    }
}